/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import Factory.ConnectionFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Usuario;


/**
 *
 * @author Felipe
 */
public class UsuarioDAO implements UsuarioDAOInterface{
    
    //código vindo do config.php
    //Deve ser somado à senha do usuario para fazer o login
    
    private final String CODEPASSWORD = getCodePassword();
    
    private String getCodePassword(){
        String codigo = "";
        Properties properties = new Properties();
        String urlProperties = "../Configuration/moodleUrl.properties";
        File file = new File(urlProperties);
        String urlMoodle= "";
        try {
            properties.load(this.getClass().getResourceAsStream(urlProperties));
            
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        urlMoodle = properties.getProperty("url");
        System.out.println("111111111111-----"+urlMoodle);
        File diretorio = new File(urlMoodle);
        File[] arquivos = diretorio.listFiles();
        File arquivoConfig = null;
        for(int i =0; i<arquivos.length;i++){
            if(arquivos[i].getName().equals("config.php")){
                arquivoConfig = arquivos[i];
                break;
            }
        }
        try {
            FileReader fr = new FileReader(arquivoConfig);
            BufferedReader br = new BufferedReader(fr);
            String strLinha;
            while(br.ready()){
                strLinha = br.readLine();
                if(strLinha.contains("passwordsaltmain")){
                    int beginIndex = strLinha.indexOf("'");
                    int endIndex = strLinha.lastIndexOf("'");
                    codigo = strLinha.substring(beginIndex+1, endIndex);
                    break;
                }
            }
            br.close();
            fr.close();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }catch (IOException ex) {
            ex.printStackTrace();
        }
        
        System.out.println("111111111111-----"+codigo);
        return codigo;
    }
    
    @Override
    public Usuario verifyUsuario(Usuario usuario) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Usuario usuarioTemp = null;

        try {
            String query = "select * from mdl_user where username = ? and password = md5(?)";

            connection = ConnectionFactory.getInstance().getConnection();

            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setString(1, usuario.getLogin());
            preparedStatement.setString(2, usuario.getSenha()+ CODEPASSWORD);
            
            resultSet = preparedStatement.executeQuery();

            System.out.println(preparedStatement.toString());
            
            if (resultSet.next()) {
                usuarioTemp = new Usuario(resultSet.getInt("id"),resultSet.getString("username"),resultSet.getString("password"),resultSet.getString("firstname"),resultSet.getString("lastname"));
                
             }
        } catch (SQLException ex) {
            Logger.getLogger(UsuarioDAO.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException ex) {
                Logger.getLogger(UsuarioDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return usuarioTemp;
    }

    @Override
    public void updateUsuario(Usuario usuarioSession) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
